package com.leetcode.math;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class CombinationSum2 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            int num = scanner.nextInt();
            int target = scanner.nextInt();
            // 候选集有重复的数字
            int[] candidates = new int[num];
            for (int i = 0; i < num; i++) {
                candidates[i] = scanner.nextInt();
            }
            List<List<Integer>> ans = solver(candidates, target);
            System.out.println(ans);
        }
    }

    /**
     * 数组中每个数字在每个组合中最多只能使用一次
     *
     * @param candidates
     * @param target
     * @return
     */
    public static List<List<Integer>> solver(int[] candidates, int target) {
        List<List<Integer>> ans = new ArrayList<>();
        List<Integer> combination = new ArrayList<>();
        dfs(candidates, target, ans, combination, 0);
        return ans;
    }

    private static void dfs(int[] candidates, int target, List<List<Integer>> ans,
                            List<Integer> combination, int ind) {
        if (ind == candidates.length) {
            return;
        }
        if (target == 0) {
            ans.add(new ArrayList<>(combination));
            return;
        }
        // 跳过当前项
        dfs(candidates, target, ans, combination, ind + 1);
        // 选择当前项
        if (target - candidates[ind] >= 0) {
            combination.add(candidates[ind]);
            dfs(candidates, target - candidates[ind], ans, combination, ind + 1);
            combination.remove(combination.size()-1);
        }
    }
}
